L2. Valid Anagram

Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Solution - 1

第一种解决方案:将 s1, 2s 两个字符串进行复制,然后用 std::sort 对他们进行排序。检查排序后的两个字符串。

#include <iostream>
#include <string>
#include <algorithm>

class mySolution{
public:
    bool checkAnagram(const std::string& s1, const std::string& s2){
        if(s1.length() != s2.length()){ return false; }
        std::string sorted_s1 = s1, sorted_s2 = s2;
        std::sort(sorted_s1.begin(), sorted_s1.end());
        std::sort(sorted_s2.begin(), sorted_s2.end());
        return (sorted_s1 == sorted_s2);
    }
};

int main(){
	std::string s1{"listen"}, s2{"silent"};
    mySolution solution;
    std::cout << (solution.checkAnagram(s1, s2) ? "Positive" : "Negative") << std::endl;;
    return 0;
}

Solution - 2

字符计数的方法:

#include <iostream>
#include <string>
#include <vector>

class mySolution {
public:
    bool checkAnagram(const std::string& s1, const std::string& s2) {
        if (s1.length() != s2.length()){ return false; }

        std::vector<int> charCount(26, 0);
        for (char c : s1) {
            charCount[c - 'a']++;
        }
        for (char c : s2) {
            charCount[c - 'a']--;
        }
        for (int count : charCount) {
            if (count != 0) return false;
        }
        return true;
    }
};
int main() {
    std::string s1{"listen"}, s2{"silent"};
    mySolution solution;
    std::cout << (solution.checkAnagram(s1, s2) ? "Positive" : "Negative") << std::endl;
}